package com.example.demo.io.nio.socket.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: liull
 * @Description: bio实现的SocketServer
 * @Date: Created in 20:07 2020/4/6
 * @Modified By:
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器已启动");
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功");
            executorService.execute(() -> {
                handle(socket);
            });
        }
    }

    public static void handle(Socket socket) {
        try {
            byte[] buffer = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            int data;
            while ((data = inputStream.read(buffer)) != -1) {
                String s = new String(buffer, 0, data);
                System.out.println("当前线程是：" + Thread.currentThread().getName());
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
